// 📁 文件位置：config/webpack.prod.js
const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const SizePlugin  = require('size-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = (env) => merge(common, {
  // 生产模式
  mode: 'production',
  
  // 输出配置
  output: {
    path: path.resolve(__dirname, '../dist'),
    filename: '[name].[contenthash:8].js',
    chunkFilename: '[name].[contenthash:8].chunk.js',
    clean: true,
    publicPath: '/'
  },
  
  // 路径解析
  resolve: {
    alias: {
      '@': path.resolve(__dirname, '../src'),
      '@components': path.resolve(__dirname, '../src/components'),
      '@utils': path.resolve(__dirname, '../src/utils'),
      '@assets': path.resolve(__dirname, '../src/assets')
    },
    extensions: ['.js', '.json']
  },
  
  // 模块处理规则
  module: {
    rules: [
      // JavaScript 处理（生产环境优化）
      {
        test: /\.(js|ts)$/,
        exclude: /node_modules/,
        use: [
          'thread-loader',  // 多线程处理
          {
            loader: 'babel-loader',
            options: {
              cacheDirectory: true,
              // workers : 2
            }
          }
        ]
      },
      
      // CSS 处理（生产环境）
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          'postcss-loader'
        ]
      },
      
      // Less 处理（生产环境）
      {
        test: /\.less$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          'postcss-loader',
          'less-loader'
        ]
      },
      
      // 图片处理
      {
        test: /\.(png|jpe?g|gif|svg)$/i,
        type: 'asset/resource',
        generator: {
          filename: 'images/[name].[hash:8][ext]'
        },
        parser: {
          dataUrlCondition: {
            maxSize: 8 * 1024 // 8KB
          }
        }
      },
      
      // 字体处理
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/i,
        type: 'asset/resource',
        generator: {
          filename: 'fonts/[name].[hash:8][ext]'
        }
      }
    ]
  },
  
  // 插件配置
  plugins: [
    // CSS 提取插件
    new MiniCssExtractPlugin({
      filename: '[name].[contenthash:8].css',
      chunkFilename: '[name].[contenthash:8].chunk.css'
    }),
    
    // Gzip 压缩插件
    new CompressionPlugin({
      algorithm: 'gzip',
      test: /\.(js|css|html|svg)$/,
      threshold: 8192,
      minRatio: 0.8
    }),
    
    // Bundle 分析插件（可选）
    ...(env && env.analyze ? [
      new BundleAnalyzerPlugin({
        analyzerMode: 'static',
        openAnalyzer: false,
        reportFilename: 'bundle-report.html'
      })
    ] : []),

    // 文件大小分析插件
    new SizePlugin({
      reportFilename: 'size-report.html',     // 生成的 HTML 报告路径
      open: false,                            // 构建后是否自动打开浏览器
      include: ['js', 'css'],                 // 只统计 JS 和 CSS
      gzip: true,                             // 显示 Gzip 后的大小
      brotli: false                           // 是否显示 Brotli 大小（可选）
    }),

    // 复制 Shoelace 静态资源
    new CopyWebpackPlugin({
      patterns: [
        {
          from: path.resolve(__dirname, '../node_modules/@shoelace-style/shoelace/dist/assets'),
          to: 'shoelace/assets',
          globOptions: {
            ignore: ['**/*.d.ts']
          }
        }
      ]
    })
  ],
  
  // 优化配置
  optimization: {
    // 代码压缩
    minimizer: [
      // JavaScript 压缩
      new TerserPlugin({
        terserOptions: {
          compress: {
            drop_console: true,    // 移除 console
            drop_debugger: true    // 移除 debugger
          }
        }
      }),
      // CSS 压缩
      new CssMinimizerPlugin()
    ],
    
    // 代码分割
    splitChunks: {
      chunks: 'all',
      maxInitialRequests: 6, // 增加并行加载数量
      maxAsyncRequests: 6,
      cacheGroups: {
        // Polyfills 单独分包
        polyfills: {
          test: /[\\/]node_modules[\\/]core-js/,
          name: 'polyfills',
          chunks: 'all',
          priority: 15
        },
        // 第三方库
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all',
          priority: 10,
          maxSize: 244000, // 限制单个包大小约240KB
          minSize: 20000   // 最小包大小20KB
        },
        // 公共代码
        common: {
          name: 'common',
          minChunks: 2,
          chunks: 'all',
          priority: 5,
          reuseExistingChunk: true,
          maxSize: 244000
        }
      }
    },
    
    // 运行时代码分离
    runtimeChunk: 'single',
    
    // 模块 ID 生成策略
    moduleIds: 'deterministic',
    
    // Tree Shaking : 树摇 AST树
    usedExports: true,
    sideEffects: false
  },
  
  // 缓存配置
  cache: {
    type: 'filesystem',
    buildDependencies: {
      config: [__filename]
    }
  }
});